package org.example.ioc_01;


import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class getBeanFromIoc {
    @Test
    public void getBean(){
        //1、创建ioc容器对象
        //方法1
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-01.xml");
        //方法2
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext();
        classPathXmlApplicationContext.setConfigLocation("spring-01.xml");
        classPathXmlApplicationContext.refresh();
        //2、DI
        //这种方式获bean,当有多个bean是同类型时会报错
        HappyComponent happyComponent = applicationContext.getBean(HappyComponent.class);
        happyComponent.doWork();
        //需要强转
        HappyComponent happyComponent1 = (HappyComponent) applicationContext.getBean("happyComponent");
        happyComponent1.doWork();
        //
        HappyComponent happyComponent2 = applicationContext.getBean("happyComponent", HappyComponent.class);


    }
    @Test
    public void test(){
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-01.xml");
//        applicationContext.refresh();
        HappyComponent happyComponent2 = applicationContext.getBean("happyComponent", HappyComponent.class);
        happyComponent2.doWork();
        applicationContext.close();
    }
    @Test
    public void test1(){
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-01.xml");
//        applicationContext.refresh();
        JavaFactoryBean javaFactoryBean = applicationContext.getBean("javaFactoryBean", JavaFactoryBean.class);
        System.out.println(javaFactoryBean);
        Object bean = applicationContext.getBean("&javaFactoryBean");
        System.out.println(bean);
        applicationContext.close();
    }
}
